package com.db.dbdocument.generateDB.common;

import com.db.dbdocument.generateDB.query.clickhouse.ClickhouseDataBaseQuery;
import com.db.dbdocument.generateDB.query.mysql.MysqlDataBaseQuery;
import com.db.dbdocument.generateDB.vo.DbTableInfoVo;
import com.db.dbdocument.generateDB.vo.DbTableStructureInfoVo;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.*;

public class DataSoreceConnect {

    /**
     * 获取表
     */
    public static List<DbTableInfoVo> getTable(String url,List<Map<String,Object>> mapList){
        List<DbTableInfoVo> dbTableInfoVoList = new ArrayList<>();

        if (url.contains(":mysql:")){
            dbTableInfoVoList = MysqlDataBaseQuery.getTableInfo(mapList);
        }else if (url.contains(":clickhouse:")){
            dbTableInfoVoList = ClickhouseDataBaseQuery.getTableInfo(mapList);
        }

        return dbTableInfoVoList;
    }


    /**
     * 获取表字段 公共类
     */
    public static List<DbTableStructureInfoVo> getTableStructure(String url,Connection connection) throws SQLException {
        List<DbTableStructureInfoVo> dbTableStructureInfoVoList = new ArrayList<>();

        if (url.contains(":mysql:")){
            dbTableStructureInfoVoList = MysqlDataBaseQuery.getTableStructureInfo(connection);
        }else if (url.contains(":clickhouse:")){
            dbTableStructureInfoVoList = ClickhouseDataBaseQuery.getTableStructureInfo(connection);
        }

        return dbTableStructureInfoVoList;
    }


    /**
     * ResultSet 转换 listmap
     */
    public static List<Map<String,Object>> rsConvertListMap(ResultSet resultSet) throws SQLException {
        ResultSetMetaData meta = resultSet.getMetaData();
        int cot = meta.getColumnCount();

        List<Map<String, Object>> listmap = new ArrayList();
        while(resultSet.next()) {
            Map<String, Object> map = new HashMap();
            for(int i = 0; i < cot; i++) {
                map.put(meta.getColumnName(i + 1), resultSet.getObject(i + 1));
            }
            listmap.add(map);
        }

        return listmap;
    }



    /**
     * 释放资源
     *
     * @param rs {@link ResultSet}
     */
    public static void close(ResultSet rs) {
        if (!Objects.isNull(rs)) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 释放资源
     *
     * @param conn {@link Connection}
     */
    @SuppressWarnings("DuplicatedCode")
    public static void close(Connection conn) {
        if (!Objects.isNull(conn)) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 释放资源
     *
     * @param rs   {@link ResultSet}
     * @param conn {@link Connection}
     */
    @SuppressWarnings("DuplicatedCode")
    public static void close(ResultSet rs, Connection conn) {
        if (!Objects.isNull(rs)) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (!Objects.isNull(conn)) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 释放资源
     *
     * @param rs   {@link ResultSet}
     * @param st   {@link Statement}
     * @param conn {@link Connection}
     */
    @SuppressWarnings("DuplicatedCode")
    public static void close(ResultSet rs, Statement st, Connection conn) {
        if (!Objects.isNull(rs)) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (!Objects.isNull(st)) {
            try {
                st.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (!Objects.isNull(conn)) {
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }




    public static void main(String[] args) throws IOException, SQLException {
        String path =  System.getProperty("user.dir")+"/src/main/resources/properties/mysql.properties";
        File file = new File(path);
        FileInputStream fileInputStream = new FileInputStream(file);
        Properties properties = new Properties();
        properties.load(fileInputStream);

        System.out.println(properties);
        //数据源
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(properties.get("driver").toString());
        hikariConfig.setJdbcUrl(properties.get("url").toString());
        hikariConfig.setUsername(properties.get("username").toString());
        hikariConfig.setPassword(properties.get("password").toString());
        //设置可以获取tables remarks信息
        hikariConfig.addDataSourceProperty("useInformationSchema", "true");
        hikariConfig.setMinimumIdle(2);
        hikariConfig.setMaximumPoolSize(5);
        DataSource dataSource = new HikariDataSource(hikariConfig);

        //数据库名称
        String cataLog =  dataSource.getConnection().getCatalog();
        //数据库架构
        String schema = dataSource.getConnection().getSchema();
        //获取表信息
        ResultSet tables = dataSource.getConnection().getMetaData().getTables(cataLog, schema, "%", new String[]{"TABLE"});

        int columnCount = tables.getMetaData().getColumnCount();

        //存放列名和结果
        List<Map<String, Object>> values = new ArrayList<>(16);

        while (tables.next()){
            Map<String,Object> map = new HashMap<>();
            for (int i=1;i<=columnCount;i++){
                map.put(tables.getMetaData().getColumnName(i),tables.getObject(i));
                System.out.println(tables.getMetaData().getColumnName(i)+"-----"+tables.getObject(i));
            }
            values.add(map);
        }
    }
}
